﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

public class GetDataFromApi
{
    // get请求
    public static T SendGetRequest<T>(string url, Dictionary<string, string> dict_data)
    {
        StringBuilder sb = new StringBuilder("");
        foreach (KeyValuePair<string, string> kvp in dict_data)
        {
            sb.Append(kvp.Key + "=" + kvp.Value);
            sb.Append('&');
        }
        string data = sb.ToString();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url+"?" + data.Substring(0, data.Length - 1));
        request.Method = "GET";
        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string result = reader.ReadToEnd();
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        serializer.MaxJsonLength = int.MaxValue;
                        return serializer.Deserialize<T>(result);
                    }
                }
            }
        }
        catch { }
        return default(T);
    }

    // post请求
    public static T SendPostRequest<T>(string method, object data)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.MaxJsonLength = int.MaxValue;
        string json = serializer.Serialize(data);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(method);
        request.Method = "POST";
        request.ContentType = "application/json";
        try
        {
            using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(json);
            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string result = reader.ReadToEnd();
                        JavaScriptSerializer serializer1 = new JavaScriptSerializer();
                        serializer1.MaxJsonLength = int.MaxValue;
                        return serializer1.Deserialize<T>(result);
                    }
                }
            }
        }
        catch { }
        return default(T);
    }

}

